﻿using System;
using System.Text;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools.Database.Generator
{
    public class CodeTextBuilder
    {
        readonly StringBuilder
            builder;
        int
            openScopes = 0;

        public CodeTextBuilder()
        {
            this.builder = new StringBuilder();
        }

        void EmitIdent()
        {
            for (int i = 0; i < this.openScopes; i++)
                this.builder.Append('\t');
        }

        public void OpenScope()
        {
            EmitIdent();
            this.builder.AppendLine("{");

            ++this.openScopes;
        }

        public void CloseScope()
        {
            if (this.openScopes == 0)
                throw new Exception("scope is not open");

            --this.openScopes;

            EmitIdent();
            this.builder.AppendLine("}");
        }

        public void AppendLine(string text, params object[] objs)
        {
            EmitIdent();
            this.builder.AppendFormat(text, objs);
            this.builder.AppendLine();
        }

        public override string ToString()
        {
            if (this.openScopes > 0)
                throw new Exception("scope is not closed");

            return this.builder.ToString();
        }
    }
}
